package com.sergio.compress.model.base;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sergio.compress.dao.model.CpTestRecord;
import com.sergio.compress.dao.model.SeTestRecord;
import com.sergio.compress.service.CompressTestService;
import com.sergio.compress.utils.SpringContextHolder;

import java.util.ArrayList;
import java.util.List;

public abstract class ChannelWrapper<T> {

    public abstract Class<T> getMainClazz();

    public abstract String getChannelName();

    public boolean resultSe;
    public long timeSe;
    public long timeDse;

    public int lengthSource;


//    public List<T> data;

    public T dataSend;

    //压缩测试的结果
    public List<CpTestRecord> cpResults;

    public void addData(T dataSource) {
        this.dataSend = dataSource;
    }

    ;

    public abstract byte[] serialize();

    public abstract void deserialize(byte[] source);

    public byte[] cpTest(byte[] d1, SeTestRecord dataTestRecord) {
        try {
            this.cpResults = SpringContextHolder.getBean(CompressTestService.class).makeTest(d1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d1;
    }

    public List<SeTestRecord> doTest(T dataSource, Integer lengthSourceSe) {
        SeTestRecord dataTestRecord = new SeTestRecord();
        dataTestRecord.setLengthSource(lengthSourceSe);
//        dataTestRecord.setInfoLength(dataSource.size());
        dataTestRecord.setChannelType(getChannelName());
        addData(dataSource);
        byte[] d1 = serialize();
        dataTestRecord.setCostTimeSe(this.timeSe);
        dataTestRecord.setLengthSe((long) d1.length);
        dataTestRecord.makeSeRate();
        deserialize(cpTest(d1, dataTestRecord));
        dataTestRecord.setResultSe(this.resultSe);
        dataTestRecord.setCostTimeDse(this.timeDse);
//        System.out.println(dataTestRecord);

        List<SeTestRecord> records = new ArrayList<>();
        if (null != cpResults && !cpResults.isEmpty()) {
            for (CpTestRecord cpTestRecord : cpResults) {
                records.add(dataTestRecord.mixCpResult(cpTestRecord));
            }
        } else {
            records.add(dataTestRecord);
        }
        return records;
    }

    @Override
    public String toString() {
        return "ProtoWrapper{" +
                "resultSe=" + resultSe +
                ", timeSe=" + timeSe +
                ", timeDse=" + timeDse +
                ", lengthSource=" + lengthSource +
                '}';
    }

}
